package com.young.springdemo.service.strategy;

import lombok.extern.java.Log;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
@Log
public class InspectionSolverChooser implements ApplicationContextAware {
    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    private Map<String, InspectorSolver> chooseMap = new HashMap<>();

    public InspectorSolver choose(String type) {
        return chooseMap.get(type);
    }

    @PostConstruct
    public void register() {
        Map<String, InspectorSolver> solverMap = context.getBeansOfType(InspectorSolver.class);
        for (InspectorSolver solver : solverMap.values()) {
            for (String supports : solver.supports()) {
                chooseMap.put(supports, solver);
            }
        }
        log.info("策略模式注册"+chooseMap.size() +"条指定策略");
    }
}
